﻿using CommonDevelop;
using CommonDevelop.DB;
using CommonFP;
using ManageDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ManageRepository
{
    /// <summary>
    /// 公司数据层接口
    /// </summary>
    public interface ICompanyRepository : IBase<Base_Company>
    {
        Base_Company GetCompanyByCode(string CompanyCode);
    }
    /// <summary>
    /// 公司数据层
    /// </summary>
    public class CompanyRepository : DBBase<Base_Company>, ICompanyRepository
    {
        /// <summary>
        /// 通过code获取公司
        /// </summary>
        public Base_Company GetCompanyByCode(string CompanyCode)
            => string.IsNullOrWhiteSpace(CompanyCode) ? null :
            SugarBizDB.GetReadOnlyOne<Base_Company>(a => a.CompanyCode.Equals(CompanyCode));

        /// <summary>
        /// 关键字查询，确认查询条件
        /// </summary>
        public override Expression<Func<Base_Company, bool>> WhereKeyWord(string keyword)
            => t => t.FullName.Contains(keyword) || t.CompanyCode.Contains(keyword);

        /// <summary>
        /// 拉关系
        /// </summary>
        public override IEnumerable<TVO> GetPull<TVO>(Base_Company en)
        {
            if (en == null)
                return base.GetPull<TVO>(en);

            if (typeof(TVO).Equals(typeof(Base_Company)))
            {
                List<Base_Company> result = new List<Base_Company>();
                en.CompanyId.ToOption()
                    .Map(a => this.GetList(d => d.ParentId == a))
                    .ForEach(a => result.AddRange(a));

                return result.Cast<TVO>().ToList();
            }
            else
                return base.GetPull<TVO>(en);
        }
        /// <summary>
        /// 推关系
        /// </summary>
        public override IEnumerable<Base_Company> GetPush<TVO>(TVO en)
        {
            var result = base.GetPush<TVO>(en);
            if (en == null)
                return result;

            if (typeof(TVO).Equals(typeof(Base_Company)))
            {
                (en as Base_Company)
                    .ToOption()
                    .Map(a => this.GetEntity(m => m.CompanyId.Equals(a.ParentId), false))
                    .ForEach(a => result.Append(a));

                return result;
            }
            else
                return result;
        }
    }
}
